$(function () {
    for (var i = 0; i < 5; i++) {
        var $tr = $("<tr id='" + (i + 1) + "' style='text-align:center;'>" +
            "<td>" + (i + 1) + "</td>" +
            "<td style='text-align:right;'>" +
            "<input style='width: 320px;' class='layui-input' type='text' id='goodsName" + (i + 1) + "' readonly  value=''>" +
            "<input  type='hidden' id='goodsId" + (i + 1) + "'  value=''>" +
            "</td>" +
            "<td>" +
            "个" +
            "</td>" +
            "<td>" +
            "<input class='layui-input' onkeyup='updNum(" + (i + 1) + ")'  type='text' id='quantity" + (i + 1) + "'  value=''>" +
            "<input type='hidden' id='oldQuantity" + (i + 1) + "'  value=''>" +
            "</td>" +
            "<td>" +
            "<input class='layui-input'  readonly  type='text' id='salesPrice" + (i + 1) + "'  value=''>" +
            "</td>" +
            "<td>" +
            "<input class='layui-input'  readonly  type='text' id='available" + (i + 1) + "'  value=''>" +
            "</td>" +
            "<td>" +
            "<input class='layui-input' readonly  type='text' id='totalAmount" + (i + 1) + "'  value=''>" +
            "</td>" +
            "<td style='text-align:center;'>" +
            "<input type='button' class='layui-btn-sm layui-btn'  onclick=addGoods(" + (i + 1) + ") value='选择'>" +
            "<input type='button' class='layui-btn-danger layui-btn-sm layui-btn' onclick=del(" + (i + 1) + ") value='移除'>" +
            "</td></td>");
        $("#detail").append($tr);
    }
});
function add(i) {
    var length = $('table tr').length;
    var $tr = $("<tr id='" + length + "'  style='text-align:center;' >" +
        "<td >" + (length) + "</td>" +
        "<td style='text-align:right;'>" +
        "<input style='width: 320px;' class='layui-input' type='text' id='goodsName" + length + "' readonly  value=''>" +
        "<input  type='hidden' id='goodsId" + length + "'  value=''>" +
        "</td>" +
        "<td>" +
        "个" +
        "</td>" +
        "<td>" +
        "<input class='layui-input' onkeyup='updNum(" + length + ")'  type='text' id='quantity" + length + "'  value=''>" +
        "<input type='hidden' id='oldQuantity" + length + "'  value=''>" +
        "</td>" +
        "<td>" +
        "<input class='layui-input' readonly  type='text' id='salesPrice" + length + "'  value=''>" +
        "</td>" +
        "<td>" +
        "<input class='layui-input' readonly  type='text' id='available" + length + "'  value=''>" +
        "</td>" +
        "<td>" +
        "<input class='layui-input' readonly type='text' id='totalAmount" + length + "'  value=''>" +
        "</td>" +
        "<td style='text-align:center;'>" +
        "<input type='button' class='layui-btn-sm layui-btn'  onclick=addGoods(" + length + ") value='选择'>" +
        "<input type='button' class='layui-btn-danger layui-btn-sm layui-btn' onclick=del(" + length + ") value='移除'/>" +
        "</td></tr>");
    $("#detail").append($tr);
}
function del(index) {
    var length = $('table tr').length;//获取表格的长度
    if ($('table tr').length == 2) {//判断表格是否只剩表头加属性共两行
        alert("已经是最后一行");
    } else {
        var to = $("#total").val() * 1 - $("#totalAmount" + index).val() * 1;
        $("#total").val(to);
        $("tr[id='" + index + "']").remove();//移除当前行
        for (var i = index + 1; i < length; i++) {
            $("tr[id=\'" + i + "\']")
                .replaceWith("<tr id='" + (i - 1) + "' align='center'>" +//把后一行的索引减一，索引号和顺序一一对应
                    "<td>" + (i - 1) + "</td>" +
                    "<td style='text-align:right;'>" +
                    "<input style='width: 320px;' class='layui-input' type='text' id='goodsName" + (i - 1) + "' readonly  value='" + $("#goodsName" + i).val() + "'>" +
                    "<input  type='hidden' id='goodsId" + (i - 1) + "'  value='" + $("#oldGoodsId" + (i - 1)).val() + "'>" +
                    "</td>" +
                    "<td>" +
                    "个" +
                    "</td>" +
                    "<td>" +
                    "<input class='layui-input' type='text' onkeyup='updNum(" + (i - 1) + ")' id='quantity" + (i - 1) + "' value='" + $("#quantity" + i).val() + "'>" +
                    "<input type='hidden' id='oldQuantity" + (i - 1) + "'  value='" + $("#oldQuantity" + (i - 1)).val() + "'>" +
                    "</td>" +
                    "<td>" +
                    "<input class='layui-input' type='text' id='salesPrice" + (i - 1) + "' readonly   value='" + $("#salesPrice" + i).val() + "'>" +
                    "</td>" +
                    "<td>" +
                    "<input class='layui-input' type='text' id='available" + (i - 1) + "' readonly   value='" + $("#available" + i).val() + "'>" +
                    "</td>" +
                    "<td>" +
                    "<input class='layui-input' type='text' id='totalAmount" + (i - 1) + "' readonly  value='" + $("#totalAmount" + i).val() + "'>" +
                    "</td>" +
                    "<td style='text-align:center;'>" +
                    "<input type='button' class='layui-btn-sm layui-btn'  onclick=addGoods(" + (i - 1) + ") value='选择'>" +
                    "<input type='button' class='layui-btn-danger layui-btn-sm layui-btn' onclick=del(" + (i - 1) + ") value='移除'></td>" +
                    "</tr>");

        }

    }
}
function getDetail(obj) {
    return obj;
}
function getCus(obj) {
    return obj;
}
function getDetail(obj) {
    return obj;
}

function addGoods(i) {
    layui.use(['layer'], function () {
        var length = document.getElementById("myTable").rows.length;//获取表格长度
        var layer = layui.layer;
        layer.open({
            //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            type: 2,
            area: ['600px', '380px'],
            content: 'goodsDetail.html',
            success: function (layero, index) {
                // 获取子页面的iframe
                var iframe = window['layui-layer-iframe' + index];
                //调用子页面的全局函数
                iframe.getIndex(i, length);
            }
        });
    });
}

layui.use(['laydate', 'form', 'layer'], function () {
    var laydate = layui.laydate;
    var form = layui.form;
    var layer = layui.layer;
    //选择客户
    $("#customer").click(function () {
        layer.open({
            type: 2,
            area: ['600px', '380px'],
            content: 'cusList.html',
            success: function (layero, index) {
                var iframe = window['layui-layer-iframe' + index];
                //调用子页面的全局函数
                iframe.getCustomer();
            }
        })
    });
    //渲染时间
    laydate.render({
        elem: '#orderExpirationTime',
        value: new Date()
    });
    laydate.render({
        elem: '#createDate',
        value: new Date()
    });
    //表单验证
    form.verify({
        customer: function (value) {
            if (value == "") {
                return "请选择客户!"
            }
        },
        payStatus: function (value) {
            if (value == "") {
                return "请选择付款状态"
            }
            if (value == 1 && $("#amountPaid").val() != 0) {
                return "未付款时的实付金额应等于0"
            }
            if (value == 2 && ($("#amountPaid").val() == 0 || $("#amountPaid").val() >= $("#total").val())) {
                return "部分付款时的实付金额应小于应付金额"
            }
            if (value == 3 && $("#amountPaid").val() != $("#total").val()) {
                return "付全款时的实付金额应等于应付金额"
            }
        },
        amountPaid: function (value) {
            var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
            if (value == "") {
                return "请输入付款金额"
            }
            if (!reg.test(value)) {
                return "金额格式不正确"
            }
            if (value > $("#total").val()) {
                return "实付金额不能大于总金额"
            }
        },
        createDate: function (value) {
            if (value == "") {
                return "请输入有效日期"
            }
        },
        totalAmount: function (value) {
            if (value == "" || value == 0) {
                return "您还未选择商品"
            }
        },
        orderExpirationTime: function (value) {
            if (value == "") {
                return "请输入有效日期"
            } else if (value != "" && $("#createDate").val() != "") {
                var arr = $("#createDate").val().split("-"); //log [2016,04,06]
                var start = new Date(arr[0], (arr[1] - 1), arr[2]);
                var starts = start.getTime(); //输出时间戳进行对比
                var arrs = value.split("-");
                var end = new Date(arrs[0], (arrs[1] - 1), arrs[2]);
                var ends = end.getTime();
                if (starts >= ends) {
                    return '有效日期必须大于单据日期';
                }
            }
        }
    });
    form.on('submit(handin)', function (data) {
        var flag = true;
        var arr = [];
        var info;
        var order = {
            "customerId": parseInt($("#customerId").val()),
            "createDate": $("#createDate").val(),
            "orderExpirationTime": $("#orderExpirationTime").val(),
            "paymentStatus": parseInt($("#orderStatus").val()),
            "amountPaid": parseInt($("#amountPaid").val()),
            "totalAmount": parseInt($("#total").val())
        };
        var k = 0;
        var length = $('table tr').length;//获取表格长度
        for (var i = 1; i < length; i++) {
            if ($("#quantity" + i).val() != "" && $("#goodsName" + i).val() != "") {//如果表格内容不为空
                k = k + 1;
                info = {
                    "goodsId": parseInt($("#goodsId" + i).val()),
                    "quantity": parseInt($("#quantity" + i).val()),
                    "detailTotal": parseInt($("#totalAmount" + i).val())
                };
                arr.push(info);//添加订单明细对象
            }
            if ($("#quantity" + i).val() == "" && $("#goodsName" + i).val() != "") {
                flag = false;
            }
        }
        var orderUtil = {
            "order": order,
            "list": arr
        };
        if (flag == true) {
            $.ajax({
                url: "Order/addOrder",
                contentType: "application/json;charset=UTF-8;",
                data: JSON.stringify(orderUtil),
                type: "post",
                traditional: true,
                dataType: "json",
                success: function (data) {
                    if (data.obj != null) {
                        layer.msg("增加订单成功", { icon: 1 });
                        setTimeout(function () {
                            location.href = 'addOrder.html';
                        }, 500);
                        location.href = "addOrder.html"
                    } else {
                        layer.msg("增加订单失败,请稍后再试", { icon: 2 });
                        location.href = "addOrder.html"
                    }
                }
            })
        } else {
            layer.msg("存在未输入数量的明细项", { icon: 2 });
        }

    });
});
function updNum(k) {
    layui.use('layer', function () {
        var layer = layui.layer;

        var oldTotal = 0;
        var total = 0;
        var quantity = 0;
        var oldQuantity = 0;
        var salesPrice = 0;
        var length = $('table tr').length;//获取表格长度
        var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if ($("#goodsId" + k).val() == "") {
            layer.msg("您还未选择商品！", { icon: 2 });
            $("#quantity" + k).val("");
        } else {
            if (reg.test($("#quantity" + k).val())) {//验证数量是否合法
                if ($("#quantity" + k).val() * 1 > $("#available" + k).val() * 1 || $("#available" + k).val() * 1 < 1) {
                    layer.msg("数量已超过库存！", { icon: 2 });
                    oldTotal = $("#oldTotal").val() * 1;//获取修改之前的总金额
                    total = $("#total").val() * 1 - oldTotal;//总金额减去不合法的数据
                    $("#oldTotal").val(total);//更新订单总金额
                    $("#quantity" + k).val("");//清空数量
                    $("#total").val(total);
                    $("#oldQuantity" + k).val("");//清空旧数量
                    $("#totalAmount" + k).val("");//清空该项的总金额
                } else {
                    oldTotal = $("#oldTotal" + k).val();//获取修改之前的总金额
                    oldQuantity = $("#oldQuantity" + k).val();//获取修改之前的数量
                    quantity = $("#quantity" + k).val();//获取修改之后的数量
                    salesPrice = $("#salesPrice" + k).val();//获取单价
                    $("#totalAmount" + k).val(salesPrice * quantity);//更新该项总金额
                    for (var i = 1; i < length; i++) {
                        if ($("#salesPrice" + i).val() != "") {//如果表格内容不为空
                            total = total + $("#totalAmount" + i).val() * 1;//总金额逐项相加
                        }
                    }
                    $("#oldQuantity" + k).val(quantity);//更新修改之前的数值的值
                    $("#oldTotal").val(total);//更新修改之前总金额的值
                    $("#total").val(total);
                }
            } else {
                layer.msg("数量应该为正整数！");
                oldTotal = $("#oldTotal").val() * 1;//获取修改之前的总金额
                total = $("#total").val() * 1 - oldTotal;//总金额减去不合法的数据
                $("#oldTotal").val(total);//更新订单总金额
                $("#quantity" + k).val("");//清空数量
                $("#total").val(total);
                $("#oldQuantity" + k).val("");//清空旧数量
                $("#totalAmount" + k).val("");//清空该项的总金额
            }
        }
    });
}